import os
import sys

from PySide6.QtGui import QPixmap, Qt
from PySide6.QtWidgets import QWidget, QApplication, QHeaderView
from itemWidget import Ui_Form as itemUF
from ui import Ui_Form


def show_image_in_label(label, path):
    if not os.path.isabs(path):
        path = os.path.abspath(path)
    path = path.replace("\\", "/")
    pixmap = QPixmap(path)
    pixmap_scaled = pixmap.scaled(
        label.size(),  # 目标大小
        Qt.AspectRatioMode.KeepAspectRatio,  # 保持宽高比
        Qt.TransformationMode.SmoothTransformation  # 平滑缩放
    )
    label.setPixmap(pixmap_scaled)
class itemWidget(QWidget, itemUF):
    def __init__(self,parent=None):
        super(itemWidget, self).__init__()
        self.setupUi(self)
    def setData(self,path, name, value1, value2):
        show_image_in_label(self.label,path)
        self.label_2.setText(name)
        self.label_4.setText(str(value1))
        self.label_6.setText(str(value2))


class MainWindows(QWidget, Ui_Form):
    def __init__(self):
        super(MainWindows, self).__init__()
        self.setupUi(self)

        self.tableWidget.horizontalHeader().setVisible(False)
        self.tableWidget.verticalHeader().setVisible(False)
        self.tableWidget.setColumnCount(1)
        # 设置列和行的调整模式为自动调整大小
        self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tableWidget.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tableWidget.cellClicked.connect(self.selectItem)

        self.initUI()

    def selectItem(self, row, column):
        print(row, column)

        for i in range(self.tableWidget.rowCount()):
            item = self.tableWidget.cellWidget(i, 0)
            if self.tableWidget.cellWidget(row, column) == item:

                item.setStyleSheet("#frame{border: 2px solid #e9c378;border-radius:5px;}")
            else:
                item.setStyleSheet("#frame{border: 0px solid #e9c378}")



    def initUI(self):
        self.tableWidget.setRowCount(10)
        for i in range(10):
            item =itemWidget()
            item.setData("image1.png","图片处理",i,i)
            item.setFixedWidth(self.tableWidget.width())
            self.tableWidget.setCellWidget(i, 0, item)

    def resizeEvent(self, event):
        for i in range(self.tableWidget.rowCount()):
            item = self.tableWidget.cellWidget(i, 0)
            if item is not None:
                item.setFixedWidth(self.tableWidget.width())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindows()
    window.show()
    sys.exit(app.exec_())